<template>
  <div id="scroll-content" ref="scrollBox" class="main-content">
    <el-carousel
      arrow="always"
      ref="remarkCarusel"
      trigger="click"
      :autoplay="false"
      :height="height + 'px'"
      :loop="false"
      :initial-index="doubleIndex"
      @change="changeCa"
      :direction="direction"
    >
      <el-carousel-item v-for="(item, i) in pageData" :key="item">
        <div v-html="item" :id="'double' + i"></div>
      </el-carousel-item>
    </el-carousel>
  </div>
</template>

<script>
import chartMixins from '../../components/mixins/chartMixins'
export default {
  name: 'ReportPageContentDouble',
  mixins: [chartMixins],
  props: {
    reportId: {
      type: String,
      required: true
    },
    getTreeList: {
      type: Array,
      required: true
    },
    positionId: {
      type: String
    },
    inputSearch: {
      type: String,
      required: true
    },
    searchIndex: {
      type: Number,
      required: true
    },
    height: {
      type: Number,
      required: true
    },
    inputPage: {
      type: Number,
      required: true
    },
    doubleIndex: {
      type: Number,
      required: true
    },
    scaleSize: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      pageData: [],
      isEchartsData: [],
      chartData: {},
      homeEcharts: null,
      flag: false, //因为change不能设置冒泡事件，导致相关事件多次触发
      changeFlag: false, //因为change不能设置冒泡事件，导致相关事件多次触发
      direction: 'horizontal', // 方向垂直或则水平
      timer: '',
      scrollTimer: '',
      oldScrollDiv: '',
      newScrollDiv: ''
    }
  },
  watch: {
    reportId: {
      handler(a) {
        this.getReport(a)
      }
    },
    doubleIndex: {
      handler(a, b) {
        if (a != b) {
          if (!this.changeFlag) {
            this.flag = true
            this.$refs.remarkCarusel.setActiveItem(a)
          }
          this.changeFlag = false
        }
      }
    },
    inputSearch: {
      handler() {
        this.findInPage()
      }
    },
    searchIndex: {
      handler() {
        if (this.totalIndex > 0) {
          this.highlightCurrentToken()
        }
      }
    }
  },
  created() {
    this.getReport(this.reportId)

    // 给当前页面添加onClick事件
    window.gotoGis = form => {
      console.log(form)
      this.$emit('gotoGis', form)
    }
  },
  mounted() {
    console.log(this.$refs.remarkCarusel)
    let event = e => {
      let key = window.event.keyCode
      if (key === 37 && this.doubleIndex > 0) {
        this.doubleIndex
        this.$refs.remarkCarusel.prev()
      } else if (key === 39 && this.doubleIndex < this.pageData.length) {
        this.$refs.remarkCarusel.next()
      }
    }
    // 添加 键盘监控事件
    document.addEventListener('keyup', event)
    this.$once('hook:beforeDestroy', () => {
      document.removeEventListener('keyup', event)
    })
  },
  methods: {
    // 绑定滚动触底事件事件
    bindScroll() {
      setTimeout(() => {
        this.pageData.forEach((item, i) => {
          let scrollDiv = this.$refs.remarkCarusel.$children[i].$el
          let offsetHeight = scrollDiv.offsetHeight
          let event = () => {
            let scrollTop = scrollDiv.scrollTop
            let scrollHeight = scrollDiv.scrollHeight

            if (this.scrollTimer) {
              clearTimeout(this.scrollTimer)
            }
            if (
              offsetHeight + scrollTop >= scrollHeight &&
              this.doubleIndex < this.pageData.length - 1
            ) {
              //触发事件
              this.newScrollDiv = this.$refs.remarkCarusel.$children[i].$el
              this.changeDirection('next')
            } else if (scrollTop === 0 && this.doubleIndex > 0) {
              this.newScrollDiv = this.$refs.remarkCarusel.$children[i].$el
              this.changeDirection('prev')
            }
          }
          scrollDiv.addEventListener('scroll', event)
          this.$once('hook:beforeDestroy', () => {
            scrollDiv.removeEventListener('keyup', event)
          })
        })
      }, 200)
    },

    // 完成 切换模式为垂直
    async changeDirection(fun) {
      await this.$nextTick(() => {
        this.$refs.remarkCarusel[fun]()
      })
    },
    getElementsToSearch() {
      const e = []
      for (
        let t = 0;
        t < document.getElementsByClassName('page-item').length;
        t++
      ) {
        let n = document.getElementsByClassName('page-item')[t]
        'style' !== n.tagName.toLowerCase() &&
          'script' !== n.tagName.toLowerCase() &&
          e.push(n)
      }
      return e
    },
    /**
     * inputSearch 搜索
     */
    findInPage() {
      //判断搜索字符是否为空
      if (!this.inputSearch) {
        this.clearTokens()
        this.inputSearch = ''
        this.searchValue = ''
        this.$emit('allPageFn', 'searchIndex', 0)
        this.$emit('allPageFn', 'totalIndex', 0)
        return
      } else {
        //判断搜索条件是否已经改变
        if (this.inputSearch != this.searchValue) {
          this.searchValue = this.inputSearch
          this.clearTokens()
          let that = this
          this.getElementsToSearch().forEach(function(t) {
            window.findAndReplaceDOMText(t, {
              find: that.searchValue,
              wrap: 'mark',
              wrapClass: 'nw-token'
            })
          })
          this.setDataPositionAttribute()
          this.highlightCurrentToken()
        }
      }
    },
    clearTokens() {
      const e = document.getElementsByClassName('nw-token')
      let t = []
      for (let n = 0; n < e.length; n++) t.push(e[n].parentNode)
      for (t = Array.from(new Set(t)); e.length; )
        e[0].replaceWith(...e[0].childNodes)
      t.forEach(function(e) {
        e.normalize()
      })
    },
    setDataPositionAttribute() {
      let e = 0,
        t = this.searchValue.length,
        n = t
      const i = document.getElementsByClassName('nw-token')
      ;[...i].forEach(
        function(i) {
          let o = i.innerText.length
          i.setAttribute(this.dataAttribute, e),
            o === t
              ? ((e += 1), (n = t))
              : ((n -= o), n < 1 && ((e += 1), (n = t)))
        }.bind(this)
      ),
        i || (e = 0),
        (this.totalIndex = e)

      this.$emit('allPageFn', 'totalIndex', this.totalIndex)
    },
    highlightCurrentToken() {
      let e = document.getElementsByClassName('nw-current-token'),
        t = document.querySelectorAll(
          '.nw-token[' + this.dataAttribute + '="' + this.searchIndex + '"]'
        )
      e &&
        e.length &&
        ((e = [...e]),
        e.forEach(function(e) {
          e.classList.remove('nw-current-token')
        })),
        t &&
          t.length &&
          ((t = [...t]),
          t.forEach(function(e) {
            e.classList.add('nw-current-token')
          }))
      if (t) {
        let textNode = t[0]
        while (textNode.className != 'page-item') {
          textNode = textNode.parentNode
        }
        let page = parseInt(textNode.id.split('page')[1]) + 1
        this.$emit('allPageFn', 'inputPage', page)
        this.$parent.setDoubleIndex(page)
        let scrollParent = document.getElementsByClassName(
          'el-carousel__item is-active is-animating'
        )[0]
        if (t[0].offsetTop < scrollParent.scrollTop) {
          scrollParent.scrollTop = t[0].offsetTop
        } else if (
          scrollParent.scrollTop + scrollParent.clientHeight <
          t[0].offsetTop + t[0].offsetHeight
        ) {
          scrollParent.scrollTop =
            scrollParent.scrollTop +
            (this.getY(t[0]) + t[0].offsetHeight) -
            (scrollParent.scrollTop + scrollParent.clientHeight)
        }
      }
    },
    getY(obj) {
      return obj.offsetParent
        ? obj.offsetTop + this.getY(obj.offsetParent)
        : obj.y
        ? obj.y
        : 0
    },

    /**
     * 左右切换按钮
     */
    changeCa(index) {
      if (!this.flag) {
        this.changeFlag = true
        this.$emit('allPageFn', 'inputPage', index * 2 + 1)
        this.$emit('allPageFn', 'doubleIndex', index)
        this.nowAnchor(index * 2 + 1)
      }
      this.flag = false
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (this.newScrollDiv) {
        this.timer = setTimeout(() => {
          this.newScrollDiv.scrollTop = 50
          this.newScrollDiv = ''
        }, 300)
      }
    },

    /**
     * 获取被选中锚点
     */
    nowAnchor(page) {
      let selectId = ''
      const selectIds = this.getTreeList
        .filter(item => item.page == page || item.page == page + 1)
        .map(item => {
          return item.htmlId
        })

      console.log(selectIds, this.getTreeList, page)
      if (selectIds.length > 0) {
        selectId = selectIds[0]
      }
      this.$emit('allPageFn', 'selectIndex', selectId)
    },
    /**
     * 循环相应id重绘echarts
     */
    reDraw() {
      this.isEchartsData.forEach(item => {
        this.reDrawEcharts(item.id, item.data)
        item.hasDraw = true
      })
    },

    /**
     * 再绘制一次echarts
     */
    reDrawEcharts(item, dataVal) {
      const a = document.getElementById(item)
      if (a) {
        a.innerHTML = ''
        a.removeAttribute('_echarts_instance_')
        this.homeEcharts = this.echarts.init(document.getElementById(item))
        this.chartData = this.initChart(dataVal)
        this.homeEcharts.setOption(this.chartData, true)
      }
    },

    /**
     * 获取报告页面 内容
     */
    getReport(reportId) {
      if (reportId) {
        const that = this
        this.api.getReportHtmlPages({ reportId }).then(data => {
          const list = data.data
          this.$emit('allPageFn', 'allPage', list.length)
          this.typographyPage(list)
          setTimeout(function() {
            that.reDraw()
            const ip = that.inputPage
            const a = ip % 2 == 0 ? ip / 2 : (ip + 1) / 2
            that.$refs.remarkCarusel.setActiveItem(a - 1)

            if (that.inputSearch) {
              that.findInPage()
            }
          }, 100)
        })
      }
    },

    /**
     * 排版报告页面
     */
    typographyPage(list) {
      let arr = []
      let len = list.length % 2 == 1 ? list.length + 1 : list.length
      if (list && len > 0) {
        for (let i = 0; i < len; i += 2) {
          let a2 = ''
          const a1 = `
              <div class="page-item" id="page${i}" style="width:49%;border:1px solid #fff;box-shadow:0px 6px 13px 0px rgb(153 153 153 / 19%);">
                ${list[i].pageTop}
                <div class="w-content-wrap w-content page-box" style="width:96%;left:2%;">
                  ${list[i].html}
                </div>
                ${list[i].pageBottom}
              </div>`

          if (list[i + 1]) {
            const item = list[i + 1]
            a2 = `
                <div class="page-item" id="page${i +
                  1}" style="width:49%;border:1px solid #fff;box-shadow:0px 6px 13px 0px rgb(153 153 153 / 19%);">
                  ${item.pageTop}
                  <div class="w-content-wrap w-content page-box" style="width:96%;left:2%;">
                    ${item.html}
                  </div>
                  ${item.pageBottom}
                </div>`
          }
          const a = `<div style="display:flex;">${a1}${a2}</div>`
          arr.push(a)

          this.judgeEchart(list[i], list[i + 1], i)
        }
      }
      this.pageData = arr
      // 绑定滚动监控事件
      this.bindScroll()
    },
    /**
     * 判断是否有echarts
     */
    judgeEchart(prevItem, nowItem, i) {
      let echartValues = this.isEchartsData
      if (prevItem.echartValue) {
        let echartValue = JSON.parse(prevItem.echartValue)
        echartValue.forEach((items, _index) => {
          echartValues.push({
            id: items.id,
            data: JSON.parse(items.data),
            pageIndex: i,
            hasDraw: false
          })
        })
      }
      if (nowItem && nowItem.echartValue) {
        let echartValue = JSON.parse(nowItem.echartValue)
        echartValue.forEach((items, _index) => {
          echartValues.push({
            id: items.id,
            data: JSON.parse(items.data),
            pageIndex: i,
            hasDraw: false
          })
        })
      }
      this.isEchartsData = echartValues
    }
  }
}
</script>
<style scoped>
.main-content {
  color: #000;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC',
    'Hiragino Sans GB', SimSun, 'Helvetica Neue', Helvetica, Arial, sans-serif,
    'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';
}
</style>
